--- 模块功能：HTTP功能测试.
-- @author openLuat
-- @module http.testHttp
-- @license MIT
-- @copyright openLuat
-- @release 2018.03.23

module(...,package.seeall)

require "http"
require "sys"
require "sim"


req.ak = ""



cbFnc = function (isSuccess, msg, head, body)
    log.info("HTTP CallBack", isSuccess, msg)
    log.info("Header", "Response Header")
    io.dumpTable(head)
    local data, jsonResult, err = json.decode(body)
    if jsonResult then
        log.info("Body", "Response Body")
        io.dumpTable(data)
        if data["data"] and data["data"]["accessToken"] then
            req.ak = data["data"]["accessToken"]
        end
    else
        log.info("Body", err)
    end
end


-- cbFnc = function (isSuccess, msg, head, body)
--     log.info("HTTP CallBack", isSuccess, msg)
--     log.info("Header", "Response Header")
--     print("检验data")
--     print("data[]" .. data)
-- end

req.login = function (username, password)
    log.info("HTTP Request", "Loging in ...")
    local boundary, body = "--------------------------"..os.time()..rtos.tick(),{}
    body[#body+1] = "--"..boundary.."\r\nContent-Disposition: form-data; name=\"username\"\r\n\r\n"..username.."\r\n"
    body[#body+1] = "--"..boundary.."\r\nContent-Disposition: form-data; name=\"password\"\r\n\r\n"..password.."\r\n"
    body[#body+1] = "--"..boundary.."--\r\n"

    -- "https://mr.chunhuiinfo.com/api/auth/login"
    http.request(
        "POST",
        "https://mr.chunhuiinfo.com/api/auth/login",
        {caCert="ca.crt"},
        {
            ["Content-Type"] = "multipart/form-data; boundary="..boundary,
            ["Connection"] = "keep-alive"
        },
        body,
        10000,
        cbFnc
        )
end

req.upload = function (attribute, filePath)
    log.info("HTTP Request", "Uploading image ...")

    print(" imei is ", attribute.imei)
    print(" iccid is ", attribute.iccid)

    local boundary, body = "--------------------------"..os.time()..rtos.tick(),{}
    body[#body+1] = "--"..boundary.."\r\nContent-Disposition: form-data; name=\"attribute\"\r\n\r\n"..json.encode(attribute).."\"\r\n"
    body[#body+1] = "--"..boundary.."\r\nContent-Disposition: form-data; name=\"file\"; filename=\"image.jpg\"\r\n\r\n"
    body[#body+1] = {file = filePath}
    body[#body+1] = "\r\n"
    body[#body+1] = "--"..boundary.."--\r\n"

    http.request(
        "POST",
        "https://mr.chunhuiinfo.com/api/image/single",
        {caCert="ca.crt"},
        {
            ["Content-Type"] = "multipart/form-data; boundary="..boundary,
            ["Connection"] = "keep-alive",
            ["Authorization"] = "Bearer " .. req.ak
        },
        body,
        30000,
        cbFnc
        )
end

req.login("admin", "123456", cbFnc)

